// pages/staff/chooseCourse/applyfree/applyfree.js
const app = getApp()
var CONFIG = require("../../../../config/config.js");
var share = require("../../../../utils/share.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    stu: [],
    stu_id: '',
    desc: '',
    textfalse: false,
    yue: '',
    buttonclick: false,
    butfalse:true,
    showfalse: false,
    text: '',
    showfalse1: false,
    text1: '',
    moneyfree: [{ index: 0, title: "请选择" }, { index: 3, title: "小七币" }, { index: 2, title: "人民币" }],   //类型
    moneyfree_index: 0,
    zk_index:0,
    discount_name:'',
    is_train:0,
    discount_id:'',
    discount_id2:'',
    product:[],
    zkarr:[],
    is_tk_price:0,
    discountsId:'',
    discoun_price:'',
    attrList:[],
    repeat_price:0,
    frist_nameN:0,
    pPrice:0,
    islink:true
  },

    getDiscountPrice(){
        var that = this;
        wx.showLoading({
            title: '加载中~',
            mask: true
        })
        var stu = that.data.stu;
        var formData = {
            course_id:stu.course_id,//	是	int	课程ID
            discount_id:that.data.discountsId,//	int	折扣ID
            specs_id:'',//	否	int	规格ID
        }
        share.wxRequest('crmapi/user/getDiscountByPrice',formData,function(res){
            if(Number(res.data.errcode)==0){
                var data = res.data.price;
                that.setData({
                    is_tk_price: Math.round((Number(stu.account_paid) - Number(data)) * 1000000) / 1000000,
                    discoun_price:data,
                })
                // console.log(that.data.is_tk_price);
            }
            wx.hideLoading()
        })
    },
    bindzkChange(e){
        var that = this;
        var index = e.detail.value;
        if(Number(index)>0){
            let price=that.data.zkarr[index].price
            let title=that.data.zkarr[index].title
            that.setData({
                zk_index: index,
                discountsId:that.data.zkarr[index].id,
                discoun_price:price,
                is_tk_price: Math.round((Number(that.data.stu.account_paid) - Number(price)) * 1000000) / 1000000,
                discount_name: title,
            })
            // that.getDiscountPrice();
        }else{
            that.setData({
                zk_index:0,
                discountsId:'',
                is_tk_price:0
            })
        }
    },

    // 选择退款方式
    bindareaChange(e){
        var that = this;
        that.setData({
            moneyfree_index: e.detail.value,
        })
    },


    // 折扣
    zks(){
      var that = this;
      var stu = that.data.stu;
        var objdata = {
            course_id:stu.course_id,//课程ID
            // user_id:stu.user_id, //用户ID
        }
      share.wxRequest('crmapi/Market/courseAttr',objdata,function(res){
        if (Number(res.data.errcode) == 0){
            var data = res.data.data.attr;
            var obj = [{
                id:'',
                title: "请选择",
                price:0
            }]
            let arr=[]
            data.forEach(val=>{
                let title=val.frist_name==val.second_name?val.frist_name:val.frist_name + val.second_name
                let a={
                   id:val.id ,
                   title:title,
                   price:val.price ,
                }
                arr.push(a)
            })
            res.data.data.attr.forEach(v=>{
                v.disCount=0
            })
            that.setData({
              zkarr: obj.concat(arr),
              attrList:res.data.data.attr
            })
            if(Number(data.length)<1){
                wx.showToast({
                    title: '该课程暂无折扣',
                    icon: 'none'
                })
            }
        }
        wx.hideLoading();
      })
    },
    getDisCount(e){
        let attrList=this.data.attrList
        let index=e.target.dataset.index
        let disCount=e.target.dataset.type
        let oldDisCount=attrList[index].disCount
        let product=[]
        if(oldDisCount==disCount&&oldDisCount!=0){
            attrList[index].disCount=0
        }else{
            attrList[index].disCount=disCount
        }
        attrList.forEach(v=>{
            if(v.disCount!=0){
                let obj={
                    id:v.id,
                    is_type:v.disCount
                }
                product.push(obj)
            }
        })
        let repeat_price=0
        let frist_nameN=''
        let pPrice=''
        attrList.forEach(v=>{
            if(v.disCount==2||v.disCount=='2'){
                repeat_price=Number(repeat_price)+Number(v.repeat_price)
            }
            if(v.disCount!=0&&v.disCount!='0'){
                frist_nameN=frist_nameN+v.frist_name,
                pPrice=Number(pPrice)+Number(v.price)
            }
        })
        console.log(attrList);
        
        this.setData({
            product:product,
            attrList:attrList,
            repeat_price:repeat_price,
            frist_nameN:frist_nameN,
            pPrice:pPrice,
        })
        if(product.length>0){
            this.getLength()
        }
    },
    getLength(){
        // if(this.data.product.length==1){
        //     if(this.data.product[0].is_type==3){
        //         wx.showToast({
        //             title: '往期已报不可单独选择',
        //             icon: 'none'
        //         })
        //     }else{
        //         this.checkAttrRestrict()
        //     }
        // }else{
            this.checkAttrRestrict()
        // }
    },
    getreset(e){
        let attrList=this.data.attrList
        attrList.forEach(v=>{
            v.disCount=0
        })
        this.setData({
            zk_index:0,
            discountsId:'',
            discoun_price:0,
            discount_name:'',
            frist_nameN:'',
            repeat_price:0,
            pPrice:0,
            product:[],
            is_tk_price:0,
            attrList:attrList
        })
    },
    checkAttrRestrict() {
        var that = this;
        // wx.showLoading({
        //     title: '加载中~',
        // })
        var formData = {
            course_id:that.data.stu.course_id,
            pid:that.data.stu.cate_id2,
            product:that.data.product
        }
        share.wxRequest('crmapi/Market/checkAttrRestrict', formData, function(res) {
                let repeat_price=that.data.repeat_price
                let frist_nameN=that.data.frist_nameN
                let pPrice=that.data.pPrice
                let attrList=that.data.attrList
                let is_train=that.data.is_train
                // attrList.forEach(v=>{
                //     v.disCount=0
                // })
                if(res.data.msg=='连报不存在'||res.data.msg=='错误'){
                    if(that.data.product.length==1){
                        is_train=that.data.product[0].is_type
                        let price=Number(pPrice)+Number(repeat_price)
                        that.setData({
                            is_train:is_train,
                            discountsId:that.data.product[0].id,
                            discoun_price:price,
                            discount_name:frist_nameN,
                            is_tk_price: Math.round((Number(that.data.stu.account_paid) - Number(price)) * 1000000) / 1000000,
                            islink:false
                        })
                    }else{
                        let ids=[]
                        let a=0
                        formData.product.forEach(v=>{
                            if(v.is_type==3){
                                a++
                            }else{
                                ids.push(v.id)
                            }
                        })
                        // if(a==0){
                            let price=Number(pPrice)+Number(repeat_price)
                            let id=ids.join(',')
                            that.setData({
                                is_train:4,
                                // zk_index:1,
                                discountsId:id,
                                discoun_price:price,
                                discount_name:frist_nameN,
                                is_tk_price:Math.round((Number(that.data.stu.account_paid) - Number(price)) * 1000000) / 1000000,
                                islink:false
                            })
                        // }else{
                        //     attrList.forEach(v=>{
                        //         v.disCount=0
                        //     })
                        //     that.setData({
                        //         zk_index:0,
                        //         discountsId:'',
                        //         discoun_price:0,
                        //         discount_name:'',
                        //         frist_nameN:'',
                        //         repeat_price:0,
                        //         pPrice:0,
                        //         product:[],
                        //         is_tk_price:0,
                        //         is_train:0,
                        //         attrList:attrList
                        //     })
                        //     wx.showToast({
                        //         title: '当前不允许选择往期已报,请重新选择折扣',
                        //         icon: 'none'
                        //     })

                        // }
                    }
                }
                if(res.data.msg.indexOf('名额已满')!=-1){
                    // 需要用户重新选
                    attrList.forEach(v=>{
                        v.disCount=0
                    })
                    that.setData({
                        zk_index:0,
                        discountsId:'',
                        discoun_price:0,
                        discount_name:'',
                        frist_nameN:'',
                        repeat_price:0,
                        pPrice:0,
                        product:[],
                        is_tk_price:0,
                        is_train:0,
                        attrList:attrList,
                        islink:false
                    })
                    wx.showToast({
                        title: res.data.msg+',请重新选择折扣',
                        icon: 'none'
                    })
                }
                if(res.data.errcode==0){
                    let price=Number(res.data.data.price)+Number(repeat_price)
                    that.setData({
                        is_train:3,
                        // zk_index:1,
                        discountsId:res.data.data.id,
                        discoun_price:price,
                        discount_name: res.data.data.frist_name,
                        is_tk_price: Math.round((Number(that.data.stu.account_paid) - Number(price)) * 1000000) / 1000000,
                        islink:true
                    })
                }
                console.log(that.data.is_train);
                
            // wx.hideLoading()
        })
    },
    ordersclick(){
        if(this.data.product.length==1){
            if(this.data.product[0].is_type==3){
                wx.showToast({
                    title: '往期已报不可单独选择',
                    icon: 'none'
                })
            }else{
                this.setData({
                    zk_index:1,
                })
            }
        }else{
            let a=0
            this.data.product.forEach(v=>{
                if(v.is_type==3){
                    a++
                }
            })
            if(this.data.islink){
                this.setData({
                    zk_index:1,
                })
            }else{
                if(a==0){
                    this.setData({
                        zk_index:1,
                    })
                }else{
                    let attrList=this.data.attrList
                    attrList.forEach(v=>{
                         v.disCount=0
                    })
                    this.setData({
                        zk_index:0,
                        discountsId:'',
                        discoun_price:0,
                        discount_name:'',
                        frist_nameN:'',
                        repeat_price:0,
                        pPrice:0,
                        product:[],
                        is_tk_price:0,
                        is_train:0,
                        attrList:attrList
                    })
                    wx.showToast({
                        title: '当前不允许选择往期已报,请重新选择折扣',
                        icon: 'none'
                    })

                }

            }
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      let that = this;
      wx.showLoading({
        title: '加载中~',
        mask: true
      })
      // console.log(options);
      that.setData({
        stu_id: options.stu_id,
      });
      //获取课程顾问信息
        var obj = {
          uc_id:that.data.stu_id
      }
      share.wxRequest('crmapi/user/userCourse',obj,function(res){
          that.setData({
            stu: res.data.data,
            is_train:res.data.data.is_train
          }) 
          that.zks();
      })
    },
  // 用户点击右上角分享

  onShareAppMessage: function () {
    return {
      title: CONFIG.SHARETITLE,
      path: CONFIG.PATHLOGIN
    }
  },
  


    sureclick() {
        var that = this;
        that.setData({
            butfalse: true,
            showfalse: false,
        })
    },
    sureclick1() {
        var that = this;
        wx.navigateBack();
    },

    // 提交
    applyfreebtn: function (e) {
        // console.log(e);
        var that = this;
        var e1 = e.detail.value;
        var user_id = that.data.stu_id;
        var stu = that.data.stu;
        var user_id1 = that.data.stu.user_id;
        var tuiprice = e1.return;
        var account_paid = Math.floor((stu.account_paid) * 100) / 100;
        var reg = /(^[-+]?[1-9]\d*(\.\d{1,2})?$)|(^[-+]?[0]{1}(\.\d{1,2})?$)/;
        var re = /^[\u4e00-\u9fa5a-z]+$/gi;//只能输入汉字和英文字母
        var moneyfree_index = that.data.moneyfree_index;
        if(that.data.discountsId == ''){
            wx.showToast({
                title: '请选择折扣',
                icon: 'none'
            })
        }
        // else if(Number(that.data.is_train!=3)&&(Number(that.data.discountsId) == Number(stu.discount_id))){
        //     wx.showToast({
        //         title: '不能与原折扣相同',
        //         icon: 'none'
        //     })
        // }
        else{
            if(Number(that.data.is_tk_price)>0){
                if (Number(moneyfree_index) == 0){
                    wx.showToast({
                        title: '请选择退款类型',
                        icon: 'none'
                    })
                }else if (tuiprice == '') {
                    wx.showToast({
                        title: '请填写退款金额',
                        icon: 'none'
                    })
                } else if (Number(tuiprice) == 0) {
                wx.showToast({
                    title: '退款金额不能为0',
                    icon: 'none'
                })
                } else if (!reg.test(tuiprice)) {
                    wx.showToast({
                        title: '请输入正确的退款金额',
                        icon: 'none'
                    })
                } else if (Number(tuiprice) > Number(account_paid)) {
                    wx.showToast({
                        title: '退款金额不能大于已付款',
                        icon: 'none'
                    })
                }else if (e1.textWhy == '') {
                  wx.showToast({
                      title: '请输入申请原因',
                      icon: 'none'
                  })
                } else {
                    that.tuishare(e1);
                }
            }else{
                that.tuishare(e1);
            }
        }
        

    },
    tuishare(e1){
      var that = this;
      var stu = that.data.stu;
      wx.showLoading({
        title: '提交中~',
        mask: true
    })
      that.setData({
          butfalse: false,
      })
      var moneyfree_index = that.data.moneyfree_index;
        var banknamw = '';
        var banknum = '';
        var bank_code = '';
        var bank_name = '';
        if(Number(that.data.is_tk_price)>0){
            var money = e1.return;
        }else{
            var money = '';
        }
        let is_train=that.data.is_train
        let discount_id=''
        let discount_id2=''
        let discount_id3=''
        let product=[]
        if(is_train==3){
            product=that.data.product
            discount_id=''
            discount_id2=that.data.discountsId
            discount_id3=''

        }else if(is_train==4){
            product=that.data.product
            discount_id=''
            discount_id2=''
            discount_id3=that.data.discountsId
        }else{
            product=[]
            discount_id=that.data.discountsId
            discount_id2=''
            discount_id3=''

        }
        var formData = {
            admin_id:app.globalData.admin_id,
            type:3,
            id:that.data.stu_id,
            course_id:stu.course_id,//	是	int	课程ID
            money:money,
            pay_type: that.data.moneyfree[that.data.moneyfree_index].index,
            specs_id:stu.specs_id,//	否	int	规格ID
            discount_id:discount_id,//	否	int	折扣ID
            discount_id2:discount_id2,//连报折扣
            discount_id3:discount_id3,
            y_discounts:stu.discounts,//	是	int	课程原价
            discounts:stu.discounts,
            reason: e1.textWhy,//	是	string	备注
            bank_user:banknamw,
            bank_num:banknum,
            bank_code:bank_code,
            bank_name:bank_name,
            discount_name:that.data.discount_name,
            is_train:is_train,
            product:product
        }
        
      share.wxRequest('crmapi/user/submitAudit',formData,function(res){
          wx.hideLoading();
          if (Number(res.data.errcode) == 0){
            wx.setStorageSync('audit_id',res.data.data.audit_id);
              that.setData({
                  showfalse1:true
              })
          }else{
              that.setData({
                  showfalse: true,
                  text: res.data.msg,
              })
          }
      })
    },
})